package com.gmadmin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmadmin.entity.SysApi;
import com.gmadmin.mapper.SysApiMapper;
import com.gmadmin.service.SysApiService;
import com.gmadmin.entity.vo.api.SysApiVo;
import com.gmadmin.utils.CollectionBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * api服务实现类
 * </p>
 *
 * @author zhangsan
 * @since 2021-12-28
 */
@Service
public class SysApiServiceImpl extends ServiceImpl<SysApiMapper, SysApi> implements SysApiService {


    @Override
    public SysApiVo findApiByPathAndMethod(String path, String method) {
       // 直接等于判断
        QueryWrapper<SysApi> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("path", path);
        queryWrapper.eq("method", method);
        SysApi api = baseMapper.selectOne(queryWrapper);
        SysApiVo apiVo = new SysApiVo();
        if (Objects.nonNull(api)) {
            BeanUtils.copyProperties(api, apiVo);
            return apiVo;
        }

        // 根据库表正则判断
        SysApi sysApi = baseMapper.findApiByPathAndMethod(path, method);
        if (Objects.isNull(sysApi)) {
            return null;
        }
        BeanUtils.copyProperties(sysApi, apiVo);
        return apiVo;
    }

    @Override
    public List<SysApiVo> findAllIgnore() {
        QueryWrapper<SysApi> wrapper = new QueryWrapper<>();
        wrapper.eq("is_ignore", true);
        return BeanUtil.copyToList(baseMapper.selectList(wrapper), SysApiVo.class);
    }

    @Override
    public List<SysApiVo> findListByRoleIds(Set<Long> roleIds) {
        return BeanUtil.copyToList(baseMapper.findListByRoleIds(roleIds), SysApiVo.class);
    }

    @Override
    public List<SysApiVo> findListByRoleId(Long roleId) {
        return CollectionBeanUtils.copyListProperties(baseMapper.findListByRoleId(roleId), SysApiVo::new);
    }

    @Override
    public List<SysApiVo> findAllAuthApi() {
        QueryWrapper<SysApi> wrapper = new QueryWrapper<>();
        wrapper.eq("is_ignore", false);
        List<SysApi> sysApis = baseMapper.selectList(wrapper);
        return CollectionBeanUtils.copyListProperties(sysApis, SysApiVo::new);
    }

}
